package com.village.friend.utils;

import org.apache.commons.lang.StringUtils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 日期公用类
 */
public class DateUtils {
    public static final String MONTH_SHORT_FORMAT = "yyyy-MM";
    public static final String DATE_SHORT_FORMAT = "yyyy-MM-dd";
    public static final String DATE_MM_FORMAT = "yyyy-MM-dd HH:mm";
    public static final String DATE_FULL_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_NUM_FULL_FORMAT = "yyyyMMddHHmmss";
    public static final String DATE_UTE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
    public static final String DATE_TIGHT_FORMAT = "yyyyMMddHHmm";
    public static final String DATE_NUMBER_FORMAT = "yyyyMMdd";
    public static final String HOUR_SHORT_FORMAT = "HH";


    /**
     * 把字符传解析成日期
     *
     * @param time
     * @return
     */
    public static Date parseDate(String time, String pattern) {
        Date date = null;
        try {
            date = new SimpleDateFormat(pattern).parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 把日期格式化为字符串
     *
     * @param date
     * @return
     * @throws ParseException
     */
    public static String formatDate(Date date, String pattern) {
        return new SimpleDateFormat(pattern).format(date);
    }

    /**
     * 把字符先解析成日期，再格式化成字符串
     *
     * @param time
     * @return
     * @throws ParseException
     */
    public static String parseFormatDate(String time, String pattern1, String pattern2) {
        String Strdate = null;
        try {
            Date date = new SimpleDateFormat(pattern1).parse(time);
            Strdate = new SimpleDateFormat(pattern2).format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return Strdate;
    }

    /**
     * 获取系统时间
     */
    public static String getSysFullDate() {
        Calendar calendar = Calendar.getInstance();
        return new SimpleDateFormat(DATE_FULL_FORMAT).format(calendar.getTime());
    }


    /**
     * 获取系统日期"yyyy-MM-dd"（cyz于20100319增加）
     */
    public static String getSysDate() {
        Calendar calendar = Calendar.getInstance();
        return new SimpleDateFormat(DATE_SHORT_FORMAT).format(calendar.getTime());
    }

    /**
     * @param time
     * @param day
     * @return
     */
    public static String addDay(String time, Integer day) {
        return formatDate(add(parseDate(time, DATE_SHORT_FORMAT), Calendar.DATE, day), DATE_SHORT_FORMAT);
    }

    /**
     * @param time
     * @param second
     * @return
     */
    public static String addSecond(String time, Integer second) {
        return formatDate(add(parseDate(time, DATE_FULL_FORMAT), Calendar.SECOND, second), DATE_FULL_FORMAT);
    }


    /**
     * @param time
     * @param day
     * @return
     */
    public static String addMonth(String time, Integer day) {
        return formatDate(add(parseDate(time, MONTH_SHORT_FORMAT), Calendar.MONTH, day), MONTH_SHORT_FORMAT);
    }

    /**
     * 指定日期增加（年）
     *
     * @param date   指定的一个原始日期
     * @param amount 数值增量
     * @return 新日期
     */
    public static Date addYear(Date date, int amount) {
        return add(date, Calendar.YEAR, amount);
    }

    /**
     * 指定日期增加数量（年，月，日，小时，分钟，秒，毫秒）
     *
     * @param date   指定的一个原始日期
     * @param field  日历类Calendar字段
     * @param amount 数值增量
     * @return
     */
    public static Date add(Date date, int field, int amount) {
        if (date == null) {
            throw new IllegalArgumentException("The date must not be null");
        } else {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.add(field, amount);
            return c.getTime();
        }
    }

    /**
     * 判断两个日期相差多少秒
     *
     * @param pre
     * @param after
     * @return 秒时间差
     */
    public static long differentSeconds(String pre, String after) {
        DateFormat df = new SimpleDateFormat(DateUtils.DATE_FULL_FORMAT);
        try {
            Date preD = df.parse(pre);
            Date afterD = df.parse(after);
            return preD.getTime() - afterD.getTime();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * 判断两个日期相差多少天
     * differentDays("2018-10-01","2018-10-02","yyyy-MM-dd")  结果：1
     */
    public static int differentDays(String date1, String date2, String pattern) {
        Date d1 = parseDate(date1, pattern);
        Date d2 = parseDate(date2, pattern);
        int days = (int) ((d2.getTime() - d1.getTime()) / (1000 * 3600 * 24l));
        return days;
    }

    /**
     * 判断两个日期相差几个月
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static Integer differentMonth(String startDate, String endDate) {
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        start.setTime(parseDate(startDate, DATE_SHORT_FORMAT));
        end.setTime(parseDate(endDate, DATE_SHORT_FORMAT));
        int result = end.get(Calendar.MONTH) - start.get(Calendar.MONTH);
        int month = (end.get(Calendar.YEAR) - start.get(Calendar.YEAR)) * 12;
        return Math.abs(month + result);
    }

    /**
     * 根据生日获取用的年纪
     *
     * @param birthDayStr 生日字符串
     * @return
     */
    public static int getAge(String birthDayStr) {
        Date birthDay = parseDate(birthDayStr, DATE_SHORT_FORMAT);

        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            return 0;
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }

    /**
     * 判断两个日期相差多少天
     * differentDays("2018-10-01","2018-10-02","yyyy-MM-dd")  结果：1
     */
    public static int getVipDays(String vipEnd) {
        if (StringUtils.isEmpty(vipEnd)) {
            return 0;
        }
        Date d1 = new Date();
        Date d2 = parseDate(vipEnd, DATE_FULL_FORMAT);
        int days = (int) ((d2.getTime() - d1.getTime()) / (1000 * 3600 * 24l));
        return days;
    }

    public static Date getToday(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    public static long getCurrentZeroTime(){
        return getToday().getTime();
    }

    public static Timestamp getCurrentZeroTimestamp(){
        return new Timestamp(getCurrentZeroTime());
    }

    public static Timestamp getCurrentTimestamp() {
        return new Timestamp(System.currentTimeMillis());
    }

    public static void main(String[] args) {
        System.out.println(getVipDays("2021-09-01 00:00:00"));
    }

    /**
     * 计算 minute 分钟后的时间
     *
     * @param date
     * @param minute
     * @return
     */
    public static Date addMinute(Date date, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, minute);
        return calendar.getTime();
    }

}
